﻿using Dapper;
using ERPEF;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SkiaSharp;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [Consumes("application/json")]
    [ApiController]
    public class BsModelController : ControllerBase
    {
        private readonly MyDbContext myDbContext;

        private readonly bs_modelService _bs_ModelService;
        private readonly bs_Model_FromService _bs_Model_FromServicecs;

        public BsModelController(MyDbContext myDbContext, bs_modelService bs_modelService, bs_Model_FromService bs_Model_FromService)
        {
            this.myDbContext = myDbContext;
            this._bs_ModelService = bs_modelService;
            this._bs_Model_FromServicecs = bs_Model_FromService;
        }

        /// <summary>
        /// 产品类型查询
        /// </summary>
        /// <returns></returns>   

        [HttpGet]
        public async Task<List<bs_model>> Index()
        {

            return await _bs_ModelService.Query();
        }

        /// <summary>
        /// 查询字典
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public async Task<IActionResult> DictQuery()
        {
            var dic = await _bs_ModelService.DictQuery();
            var dict = dic.Where(c => c.dd_type == "type_unit").ToList();
            if (dict.Any())
            {
                return Ok(dict);
            }
            else
            {
                return NotFound("404");
            }
        }

        /// <summary>
        /// 查询产品名称
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> DictImagQuery()
        {
            var warehouse = await _bs_ModelService.InmgerQuery();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns> 
        [HttpPost]
        public async Task<IActionResult> AddWarehouse([FromBody] bs_model bs_Model)
        {
            if (ModelState.IsValid)
            {
                int result = await _bs_ModelService.Add(bs_Model);
                if (result > 0)
                { 
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> UpdateClient(bs_model bs_model)
        {
            if (ModelState.IsValid)
            {
                bs_model.bs_Model_Froms = null;
                int result = await _bs_ModelService.Update(bs_model);
                if (result > 0)
                {
                    //await FromDeleteModel(bs_model.bs_Model_Froms[0].model_from_id);
                    return Ok("修改成功！");
                    
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }



        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{model_id}")]
        public async Task<string> FromDelete(int model_id)
        {
            // 获取要删除的 bs_model 数据
            var model = await myDbContext.bs_Model
                .Include(m => m.bs_Model_Froms)
                .FirstOrDefaultAsync(m => m.model_id == model_id);

            if (model == null || model.IsDeleted==true)
            {
                return "未找到对应的数据";
            }

            // 检查是否存在未被删除的 bs_Model_From 数据
            var undeletedFroms = model.bs_Model_Froms.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }

            // 逻辑删除 bs_model 数据
            model.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }




        /// <summary>
        /// 产品型号分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<bs_model>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "model_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_model"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_model>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_model> fenYe = new FenYe<bs_model>()
                {
                    models = result,
                    Rows = row,
                };

                if (fenYe.models.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }



        /// <summary>
        /// 产品类型子查询
        /// </summary>
        /// <returns></returns>   
        [HttpGet]
        public async Task<List<bs_Model_From>>ModelIndex()
        {
            return await _bs_Model_FromServicecs.Query();
        }
        /// <summary>
        /// 查询字典
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public async Task<IActionResult> FromDictQuery(string where = "配料")
        {
            var dic = await _bs_Model_FromServicecs.DictQuery();
            var data = dic.Where(w => w.di_type == where).ToList();
            if (data.Any())
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns> 
        [HttpPost]
        public async Task<IActionResult> FormAdd(bs_Model_From bs_Model_From)
        {
            if (ModelState.IsValid)
            {

               
                int result = await _bs_Model_FromServicecs.Add(bs_Model_From);
                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }



        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> FormUpdateClient(bs_Model_From bs_Model_From)
        {
            if (ModelState.IsValid)
            {
                int result = await _bs_Model_FromServicecs.UpdateModel(bs_Model_From);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{model_from_id}")]
        public async Task<IActionResult> FromDeleteModel(int model_from_id)
        {
            int result = await _bs_Model_FromServicecs.Delete(model_from_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        /// <summary>
        ///分页查询
        /// </summary>
        /// <returns></returns> 
        /// 

        [HttpGet]
        public ActionResult<FenYe<bs_Model_From>> ModelFromFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "model_from_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_Model_From"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_Model_From>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_Model_From> fenYe = new FenYe<bs_Model_From>()
                {
                    modelfrom = result,
                    Rows = row,
                };

                if (fenYe.modelfrom.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }


    }
}
